/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
<div class="channel-panel">
  <div class="title" v-if="isShowTitle">{{$t('edge.channellockoverview.realtimestatuschannels')}}</div>
  <div class="channel-content">
    <div class="channels">
      <div v-for="(item, index) in lightdata" :key="item.name" class="single-channel">
        <div class="content">
          <div v-for="(channel, index2) in item.channels" :key="channel.channelnum" class="channel">
            <div class="num">{{index * 4 + index2 + 1}}</div>
            <div class="phase-direction" :style="{'background': getBgColor()}">
              <xdr-dir-selector
                  Width="65px"
                  Height="65px"
                  Widths="55px"
                  Heights="55px"
                  :showlist="directionList(channel)"
                  :roadDirection="roadDirection"></xdr-dir-selector>
            </div>
            <div v-for="lamp in channel.lamps" :key="lamp.lampcolor" class="lamps">
              <div class="lamp" @click="handleClickLamp(item.lampctrboardnum, channel.channelnum, lamp.lampcolor, lamp)"
                :class="{'redlamp': lamp.lampcolor === 1 && !lamp.selected,
                  'yellowlamp': lamp.lampcolor === 2 && !lamp.selected,
                  'greenlamp': lamp.lampcolor === 3 && !lamp.selected,
                  'activeRedlamp': lamp.lampcolor === 1 && lamp.selected,
                  'activeYellowlamp': lamp.lampcolor === 2 && lamp.selected,
                  'activeGreenlamp': lamp.lampcolor === 3 && lamp.selected}"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>
</template>

<script>
import { getMessageByCode } from '@/utils/responseMessage'
import { getChannel } from '@/api/manual'
import { getTheme } from '../../../../utils/auth.js'
import PhaseDataModel from 'openatc-components/package/kisscomps/components/IntersectionMap/crossDirection/utils'

export default {
  name: 'realtimechannel',
  components: {},
  data () {
    return {
      lamps: [{
        lampcolor: 1,
        name: '红灯',
        selected: false
      }, {
        lampcolor: 2,
        name: '黄灯',
        selected: false
      }, {
        lampcolor: 3,
        name: '绿灯',
        selected: false
      }],
      lightdata: [],
      list: [],
      loading: false,
      realTimeChannelTimer: null, // 定时器
      tableHeight: 620,
      lightMap: new Map([[1, 0], [2, 1], [3, 2], [4, 2], [5, 1], [6, 0]]), // key: light的值, 0关灯、1红、2黄、3绿 4绿闪 5黄闪 6红闪   value: 对应的板子上的灯的索引，范围0～2，分别对应红灯、黄灯、绿灯
      channelDirMap: new Map()
    }
  },
  props: {
    channelRealtimeStatusData: {
      type: Object
    },
    roadDirection: {
      type: String,
      default: 'right'
    },
    isShowTitle: {
      type: Boolean,
      default: true
    },
    isClickable: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    channelList: {
      handler: function () {
        this.handleCreateLampCtrboard()
      },
      deep: true
    },
    channelRealtimeStatusData: {
      handler: function (val) {
        this.handleRealTimeChannelData(val.channellamp)
      },
      deep: true
    }
  },
  mounted () {
    this.initData()
  },
  methods: {
    async initData () {
      this.globalParamModel = this.$store.getters.globalParamModel
      await this.getChannelList() // 自动上载通道
      this.handleCreateLampCtrboard()
      if (this.channelRealtimeStatusData) {
        this.handleRealTimeChannelData(this.channelRealtimeStatusData.channellamp)
      }
      this.lightDataAddId()
    },
    handleCreateLampCtrboard () {
      let channel = this.channelList
      let channelIdList = channel.map(ele => ele.id)
      this.lightdata = []
      if (channel.length === 0) return
      for (let i = 1; i <= 10; i++) {
        if (!this.isHasLampCtrboard(i, channelIdList)) continue
        let lamp = {}
        lamp.lampctrboardnum = i
        lamp.name = this.$t('edge.system.lampcontrolpanel') + i

        lamp.channels = []
        for (let j = 1; j <= 4; j++) {
          let channel = {}
          channel.channelnum = j
          channel.lamps = JSON.parse(JSON.stringify(this.lamps))
          lamp.channels.push(channel)
        }
        this.lightdata.push(lamp)
      }
      console.log('this.lightdata', this.lightdata)
    },
    isHasLampCtrboard (i, channelIdList) {
      let index = i * 4
      if (channelIdList.includes(index) || channelIdList.includes(index - 1) || channelIdList.includes(index - 2) || channelIdList.includes(index - 3)) {
        return true
      }
      return false
    },
    handleExclusive () {
      // 排他，保证单选
      this.lightdata.forEach(ele => {
        ele.channels.forEach(channel => {
          channel.lamps.forEach(lamp => {
            lamp.selected = false
          })
        })
      })
    },
    handleClickLamp (lampctrboard, channel, lampcolor, lamp) {
      if (!this.isClickable) return
      this.handleExclusive()
      lamp.selected = true
      this.curClickedLampInfo = {
        lampctrboard,
        channel,
        lampcolor,
        lamp
      }
      this.$emit('handleClickLamp', this.curClickedLampInfo)
    },
    clearChannelInterval () {
      if (this.realTimeChannelTimer !== null) {
        clearInterval(this.realTimeChannelTimer) // 清除定时器
        this.realTimeChannelTimer = null
      }
    },
    handleRealTimeChannelData (channelList) {
      if (!channelList) return
      this.handleExclusive()
      for (let channel of channelList) {
        let light = channel.light
        if (light === 0) continue
        let id = channel.id
        let num = parseInt(id / 4)
        let index = id % 4
        if (index === 0) {
          num--
          index = 4
        }
        if (light > 0) {
          // 非关灯状态下
          let lightindex = this.lightMap.get(light)
          if (this.lightdata[num]) {
            this.lightdata[num].channels[index - 1].lamps[lightindex].selected = true
          }
        }
      }
    },
    directionList (channel) {
      if (!channel) return
      let id = channel.id
      let data = this.channelDirMap.get(id)
      if (!data) return []
      let color = getTheme() === 'light' ? '#1E1E1E' : '#1E1E1E'
      let dirArr = []
      if (!data) return
      if (data.type === 'ped') {
        let recd = {
          id: 0,
          peddirection: this.getPed(data.peddirection),
          color: color
        }
        dirArr.push(recd)
      } else {
        for (let rec of data.direction) {
          let recd = {
            id: rec,
            color: color
          }
          dirArr.push(recd)
        }
      }
      return dirArr
    },
    getPed (data) {
      if (data.length === 0) return
      let ped = []
      let peddirections = []
      let color = getTheme() === 'light' ? '#1E1E1E' : '#1E1E1E'
      for (let walk of data) {
        let objs = {}
        objs.name = new PhaseDataModel().getSidePos(walk).name
        objs.id = walk
        objs.color = color
        peddirections.push(objs)
        peddirections = Array.from(new Set(peddirections))
      }
      ped.push(...peddirections)
      return ped
    },
    getChannelList () {
      return getChannel().then((data) => {
        let res = data.data
        if (!res.success) {
          if (res.code === '4003') {
            this.$message.error(this.$t('edge.errorTip.devicenotonline'))
            return
          }
          this.$message.error(getMessageByCode(data.data.code, this.$i18n.locale))
          return
        }
        this.channelList = res.data.data.channelList
        this.handleChannelDirection()
      }).catch(error => {
        this.$message.error(error)
        console.log(error)
      })
    },
    handleChannelDirection () {
      this.channelList.forEach((ele, i) => {
        if (ele.type === 0 || ele.type === 1 || ele.type === 3) {
          if (ele.realdir) {
            this.channelDirMap.set(ele.id, {
              type: 'phase',
              direction: ele.realdir
            })
          }
        }
        if (ele.type === 2) {
          if (ele.realdir) {
            this.channelDirMap.set(ele.id, {
              type: 'ped',
              peddirection: ele.realdir
            })
          }
        }
      })
    },
    getBgColor () {
      return getTheme() === 'light' ? '#d9ecff' : 'rgb(217, 236, 255)'
    },
    lightDataAddId () {
      // 解决通道的相位方向显示问题（从通道状态取id会缺失）
      this.channelList.forEach((ele, i) => {
        let id = ele.id
        let num = parseInt(id / 4)
        let index = id % 4
        if (index === 0) {
          num--
          index = 4
        }
        this.lightdata[num].channels[index - 1].id = id
      })
    }
  },
  destroyed () {
    this.clearChannelInterval() // 清除定时器
  }
}
</script>

<style lang="scss" scoped>
.single-channel {
  .content {
    height: 100%;
    padding: 10px 0;
    .channel {
      display: flex;
      align-items:center;
      justify-content: space-evenly;
      height: calc(25%);
    }
    .lamps {
      flex: 1;
      position: relative;
      z-index: 9;
      .lamp {
        width: 18px;
        height: 18px;
        border-radius: 50%;
        margin: 0 auto;
        cursor: pointer;
      }
      .redlamp {
        background-color: #808080;
        box-shadow: 0px 2px 2px 0px
        rgba(140, 14, 0, 0.32);
      }
      .yellowlamp {
        background-color: #808080;
        box-shadow: 0px 2px 2px 0px
        rgba(126, 127, 27, 0.32);
      }
      .greenlamp {
        background-color: #808080;
        box-shadow: 0px 2px 2px 0px
        rgba(9, 96, 0, 0.32);
      }
      .activeRedlamp {
        background-color: #ff1a00;
        box-shadow: 0px 2px 2px 0px
        rgba(140, 14, 0, 0.32);
      }
      .activeYellowlamp {
        background-color: #ffea06;
        box-shadow: 0px 2px 2px 0px
        rgba(126, 127, 27, 0.32);
      }
      .activeGreenlamp {
        background-color: #08eb18;
        box-shadow: 0px 2px 2px 0px
        rgba(9, 96, 0, 0.32);
      }
    }
  }
}
</style>
<style rel="stylesheet/scss" lang="scss">
</style>
